package com.dxy.yzs.marathon.common.exception.util;

import io.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class DateUtil {

    private static final ThreadLocal<Map<String, SimpleDateFormat>> dateFormatContainerHolder = ThreadLocal.withInitial(() -> new HashMap<>());

    /**
     * 计算目标时间距今 几分钟 几小时 几天
     * @param date
     * @return
     */
    public static String showDate(Date date) {
        if (date == null) {
            return "";
        }
        long time = (System.currentTimeMillis() - date.getTime()) / 1000;

        if (time <= 60) {
            return "刚刚";
        } else if (time <= 3600) {
            return time / 60 + "分钟前";
        } else if (time <= 86400) {
            return time / 3600 + "小时前";
        } else if (time <= (86400 * 7)) {
            return time / 86400 + "天前";
        } else {
            return format(date, "yy-MM-dd HH:mm");
        }
    }

    public static String format(Date date, String format){
        if (date == null) {
            return "";
        }
        return getDateFormat(format).format(date);
    }

    public static SimpleDateFormat getDateFormat(String dateFormatPatternStr) {
        if (StringUtils.isEmpty(dateFormatPatternStr)) {
            return null;
        }
        return dateFormatContainerHolder.get()
                .computeIfAbsent(dateFormatPatternStr, new Function<String, SimpleDateFormat>() {
                    @Override
                    public SimpleDateFormat apply(String s) {
                        return new SimpleDateFormat(s);
                    }
                });
    }

}
